#### setting environment ####
require(readr)

newspaper.names <- c("Asahi", "Chugoku", "Chunichi", "Hokkaido", "Kahoku", 
                     "Mainichi", "Nikkei", "Nishinippon", "Sankei", "Yomiuri")

#### data preparation ####
# 2019 online survey data
voter.2019 <- read_csv("survey19_abridged.csv", 
                       locale = locale(encoding = "SJIS"))

# previous studies' measures
previous.studies <- read.csv("previous_studies.csv", row.names = "Study")

# estimation results of the factor analysis models
load("FA_result.Rdata")

# posterior draws
Study2.ideal.points.draws <- t(rbind(FA.result$mcmc[[1]][, 1:10], 
                                     FA.result$mcmc[[2]][, 1:10], 
                                     FA.result$mcmc[[3]][, 1:10])) * 10
# point estimates (posterior means)
Study2.ideal.points.mean <- rowMeans(Study2.ideal.points.draws)
# ascending order of the point estimates
Study2.ideal.points.order <- order(Study2.ideal.points.mean)

#### perceived positions of newspapers ####
ideological.perception <- rep(NA, 7)
names(ideological.perception) <- c("Asahi", "Yomiuri", "Mainichi", "Nikkei", 
                                   "Sankei", "Chunichi", "Local Papers (except Chunichi)")
# Asahi
ideological.perception[1] <- mean(voter.2019$Q15_3, na.rm = TRUE)
# Yomiuri
ideological.perception[2] <- mean(voter.2019$Q15_2, na.rm = TRUE)
# Mainichi
ideological.perception[3] <- mean(voter.2019$Q15_4, na.rm = TRUE)
# Nikkei
ideological.perception[4] <- mean(voter.2019$Q15_5, na.rm = TRUE)
# Sankei
ideological.perception[5] <- mean(voter.2019$Q15_6, na.rm = TRUE)
# Chunichi
ideological.perception[6] <- mean(voter.2019$Q15_7, na.rm = TRUE)
# Local Papers
ideological.perception[7] <- mean(voter.2019$Q15_8, na.rm = TRUE)

round(ideological.perception, 2)

#### summarize the quantitative results of previous studies (Table A.2) ####
previous.studies <- rbind(previous.studies, NA)
rownames(previous.studies)[13] <- "Online survey"
previous.studies[13, match(names(ideological.perception[1:6]), colnames(previous.studies))] <- 
  ideological.perception[1:6]

# compute correlation coefficients
previous.studies.ordered <- cbind(previous.studies[, Study2.ideal.points.order], 
                                  t = apply(previous.studies, 1, cor, y = Study2.ideal.points.mean, 
                                            use = "complete.obs", method = "pearson"), 
                                  tau = apply(previous.studies, 1, cor, y = Study2.ideal.points.mean, 
                                              use = "complete.obs", method = "kendall"))
round(previous.studies.ordered, 2)